<template>

	<view class="hhbBox">
		<scroll-view :scroll-top="scrollTop" refresher-background="#e7ecfa" scroll-y="true"
			@refresherrefresh="refresherrefresh" refresher-enabled="true" :refresher-triggered='triggered'
			:lower-threshold="500" :refresher-threshold="100" class="scroll-Y" @scrolltolower="lower"
			@scroll="scroll">
			<hbh-waterfall-list :status="waterfall.status" :list="waterfall.list" :colums="colums"
				:reset="waterfall.reset" @click="onClick" @done="onDone">
				<template>
					<view v-if="waterfall.status == 'await'">
						<view class="load-txt">上拉加载更多</view>
					</view>
					<view v-else-if="waterfall.status == 'loading'">
						<view class="load-txt">加载中</view>
					</view>
					<view v-else-if="waterfall.status == 'success'">
						<view class="load-txt">加载中</view>
					</view>
					<view v-else-if="waterfall.status == 'finish'">
						<view class="load-txt">没有更多了</view>
					</view>
					<view v-else-if="waterfall.status == 'error'">
						<view class="load-txt">首次高度未达滚动高度无法触底!<br />请反馈给官方修复</view>
					</view>
					<view v-else-if="waterfall.status == 'fail'">
						<image class="load-icon" src="/static/waterfall/fail.png"></image>
						<view class="load-txt">出错了，请刷新重试</view>
					</view>
					<view v-else-if="waterfall.status == 'empty'">
						<image class="load-icon" src="/static/waterfall/empty.png"></image>
						<view class="load-txt">暂无数据</view>
					</view>
					<view v-else></view>
				</template>
			</hbh-waterfall-list>

			<view class="status-change" v-if="floatFlag" @tap="onStatusChange">
				<view>返回<br />顶部</view>
			</view>
		</scroll-view>

	</view>
</template>

<script>
	import hbhWaterfallList from "./waterfall-list"
	import {
		selectTxtNovel
	} from "@/api/index.js"
	import fileApi from "@/uni_modules/hbh-fileIo/js_sdk/index.js"
	import {
		mapMutations,
		mapState,
		mapActions
	} from "vuex"
	export default {
		components: {
			"hbh-waterfall-list": hbhWaterfallList
		},
		props: {
			pageSize: {
				type: Number,
				default: 10
			},
			pageNum: {
				type: Number,
				default: 1
			},
			columsp: {
				type: Number,
				default: 3
			}, //分割几列
			serial: {
				type: Number,
				default: 0
			},
			current: {
				type: Number
			},
			classify_id:{
				type:Number
			}
		},
		data() {
			return {
				// 异步请求相关
				ajax: {
					// 是否可以加载
					load: true,
					// 每页的请求条件
					rows: this.pageSize,
					// 页码
					page: this.pageNum,
					// 数据列表
					dataList: []
				},
				// 瀑布流组件相关
				waterfall: {
					status: "",
					reset: false,
					list: []
				},
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
				triggered: true,
				colums: this.columsp,
				limitSize: 10,
				total: 0,
				ids: "",
				srcollHeight: 0,
				isFirst:true,
				floatFlag:true
			}
		},
		watch: {
			current(newVal, oldVal) {
				if (this.serial == (this.current + 1) && this.isFirst) {
					this.getList(true);
					this.$nextTick(() => {
						const query = uni.createSelectorQuery().in(this);
						query.select('.scroll-Y').boundingClientRect(data => {
							let height = Math.floor(data.height);
							this.srcollHeight = height
						}).exec();
					})
				}
			}
		},
		mounted() {
			if (this.serial == (this.current + 1)) {
				this.getList(true);
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this);
					query.select('.scroll-Y').boundingClientRect(data => {
						let height = Math.floor(data.height);
						this.srcollHeight = height
					}).exec();
				})
			}
		},
		methods: {
			...mapActions(["txtDownTaskStore/add"]),
			refresherrefresh(e) {
				this.ids = ""
				this.triggered = true;
				setTimeout(() => {
					this.triggered = false;
					// 正常情况下接口返回应该很会很快。故意延迟调用，让用户有在刷新的体验感
					this.ajax.page = 1;
					this.ajax.load = true;
					this.getList(true);
				}, 1000)
			},
			lower: function(e) {
				this.total = 0
				this.getList();
			},
			scroll: function(e) {
				this.old.scrollTop = e.detail.scrollTop
			},
			goTop: function(e) {
				// 解决view层不同步的问题
				this.scrollTop = this.old.scrollTop
				this.$nextTick(function() {
					this.scrollTop = 0
				});
			},
			// 瀑布流组件点击事件
			onClick(data, place, parentPlace) {
				if (!data.downIcon) {
					data.downIcon = true
					this["txtDownTaskStore/add"](data)
				} else {
					uni.showToast({
						icon: "none",
						title: "已添加，下载完成后到离线书架阅读！"
					})
				}
			},
			// 瀑布流组件渲染完成
			onDone(totalHeight) {
				// 设置组件为 非重置，这行代码保留不删即可
				this.waterfall.reset = false;

				// 恢复 getList 方法的调用
				this.ajax.load = true;
				this.ajax.page++;


				if (totalHeight < this.srcollHeight) {
					// 设置组件状态为 首次高度不达滚动高度
					this.floatFlag=false
					if(this.total<8){
						this.waterfall.status = 'finish';
					}else{
						this.waterfall.status = 'error';
						
					}
				} else {
					// 设置组件状态为 等待加载
					this.waterfall.status = 'await';
					this.floatFlag=true
				}
				/**
				 * 如果你是一个追求完美的开发者，可以通过判断当前数据的长度和请求的数据长度来优化前端请求，减少不必要请求
				 * 不需要则删除
				 * */
				/**
				if(this.ajax.dataCount >= this.ajax.rows){
					this.ajax.load = true;
					this.ajax.page++;
				}
				*/
			},
			// 获取数据
			getList(val = false) {
				this.isFirst=false
				if (!this.ajax.load) {
					return;
				}
				this.ajax.load = false;
				// 设置状态为加载中
				this.waterfall.status = 'loading';
				selectTxtNovel({
					classify_id:this.classify_id,
					limitSize: this.limitSize,
					ids: this.ids
				}).then((res) => {
					// console.log(res)
					if (res.code == 200) {
						// 第一页数据执行以下代码
						if (this.ajax.page == 1) {
							// 关闭下拉

							// 设置组件状态为 重置，可供下拉刷新这类需要重置列表功能时使用
							this.waterfall.reset = true;
						}

						// 数据无效时处理
						if (!res.data || res.data.length < 1) {
							// 设置组件为 加载结束 状态
							this.waterfall.status = 'finish';
							if (val) {
								this.waterfall.status = 'empty'
								this.waterfall.list = []
								this.floatFlag=false
							}
							return;
						}

						this.total = res.total
						this.ids = (res.data.length > 0 && this.ids.length > 0) ? (this.ids +
							',' + res.data.map(item => item.id)
							.join(
								",")) : (res.data.map(item => item.id).join(","))
						res.data.forEach(async (item, index) => {
							item.isdown = false //用户是否在下载过
							item.isDecompression = false //标记小说下载完后是否解压分割了
							item.downStatus = 3 //默认未开始下载
							item.isStop = false //是否暂停下载
							item.downingSize = 0 //初始下载量大小
							item.totalSize = 0 //初始总大小
							item.process = 0 //初始下载进度
							item.isStart = false //是否开始下载
							item.downIcon = false //false可下载
							item.isSign = false //下载过本地被删除
							item.id = 'hbh' + (this.list.length + index)
							let rame = parseInt(Math.random() *
								200)
							item.ranmHeight = rame < 50 ? 100 :
								rame
							//检查本地小说与接口数组相同的数据并修改其对应状态
							const isExist = await fileApi.fileIsExist(
								`downloadTxt/${item.fileNameId}/${item.bookName+'.txt'}`
							)
							if (isExist) {
								item.downIcon = true
								item.isdown = true
							}

						})
						// 将数据赋值给瀑布流 list 属性
						this.waterfall.list = res.data;
						// 设置组件为 加载成功 状态，此时瀑布流组件开始计算当前数据的布局
						this.waterfall.status = 'success';
						/**
						 * 下方的代码为扩展其他功能的示例代码 可做参考，不需要可删除
						 * */

						// 缓存当前数据给其他需要该数据的功能使用
						if (this.ajax.page == 1) {
							this.ajax.dataList = res.data;
						} else {
							this.ajax.dataList = [...this.ajax.dataList, ...res.data];
						}
						// 记录本次数据长度，意义请看 done 事件的回调
						this.ajax.dataCount = res.data.length || 0;

						// 。。。下面不需要写代码了，等待组件渲染完成

					} else {
						this.waterfall.status = 'fail'
					}
				}).catch((err) => {
					console.log(err)
					this.waterfall.status = 'fail'
				})
			},
			// 导航状态切换演示监听
			onStatusChange() {
				this.goTop()
			},
		}
	}
</script>

<style lang="scss">
	.hhbBox {
		height: 100%;
		border-radius: 8rpx;
	}

	.scroll-Y {
		height: 100%;
	}

	.load-txt {
		padding: 0 0 20rpx 0;
		text-align: center;
		color: #999;
		font-size: 24rpx;
	}

	.load-icon {
		width: 300rpx;
		height: 300rpx;
		margin: 0 auto 20rpx auto;
		display: block;
	}

	.status-change {
		position: fixed;
		right: 10rpx;
		top: 60%;
		width: 80rpx;
		height: 80rpx;
		z-index: 100;
		font-size: 24rpx;
		border-radius: 50%;
		background-color: #0089ff;
		color: #fff;
		line-height: 1;
		opacity: .33;

		display: flex;
		flex-direction: row;
		flex-wrap: nowrap;
		justify-content: center;
		align-items: center;
		align-content: center;
	}
</style>